<template>
  <el-container class="app-container">
   <!-- <el-collapse @change="handleCollapseChange" v-model="collapseActiveName">
      <el-collapse-item :title="collapseTitle" name="1">
        <el-tabs type="border-card">
          <el-form :model="pageInfo" ref="form" label-width="80px" size="medium">
            <el-row>
              <el-col :span="8" :offset="0">
                <el-form-item prop="name" label="账号：">
                  <el-input v-model.trim='pageInfo.name' placeholder="请输入名称搜索"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="mobile" label="手机号：">
                  <el-input v-model.trim='pageInfo.mobile' placeholder="请输入手机号搜索"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" :offset="0">
                <el-form-item prop="name" label="角色：">
                  <el-select v-model="pageInfo.roleId" clearable placeholder="请选择">
                    <el-option
                      v-for="(item,index) in addformrolelist"
                      :key="index"
                      :label="item.memo"
                      :value="item.roleId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class='tx-c'>
              <el-button type="primary" icon="el-icon-search" @click="submitForm('warehouseFilterForm')">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-row>
          </el-form>
        </el-tabs>
      </el-collapse-item>
    </el-collapse>-->
    <el-header class="m-t-20">
      <el-button @click="addAccountBtn" type="primary" icon="el-icon-plus">添加用户</el-button>
    </el-header>
    <!--表格-->
    <table-view
      :columns="tableContent"
      :pageList="columnData"
      :templateDiv="{status:true,operation:true}"
    >
      <template slot="status" slot-scope="scope">
        <el-tag :type="scope.row.status?'success':'danger'" size="mini" effect="dark">{{ scope.row.status?'正常':'停用' }}
        </el-tag>
      </template>
      <template slot="operation" slot-scope="scope">
        <el-row v-if="scope.row.adminFlag">
          管理员
        </el-row>
        <el-row v-else>
          <el-button size="mini" ype="primary" @click="editBtnClick(scope.row ,'update')">编辑</el-button>
          <el-button size="mini" type="danger" @click="editBtnClick(scope.row ,'delete')">删除</el-button>
          <el-button size="mini" type="warning" @click="editBtnClick(scope.row ,'reset')">重置密码</el-button>
        </el-row>
      </template>
    </table-view>
    <!--分页-->
    <pagination-view :pagesize="pageInfo.pageSize"
                     :currentPage="pageInfo.pageNumber"
                     :total="total"
                     @size-change="sizeChange"
                     @current-change="pageChange"
    ></pagination-view>

    <!--添加编辑，重置密码弹窗-->

    <el-dialog :title="showtitle" :visible.sync="dialog" width="40%" :show-close="true" :before-close="resetForms"
               center>
      <!--添加form-->
      <el-form
        v-show="showType==='add' || showType === 'view'"
        :model="addform"
        :rules="addformrules"
        ref="addform"
        label-width="130px"
      >
        <el-form-item label="账号名称：" prop="name">
          <el-input v-model="addform.name" :disabled="showType!=='add'"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realName">
          <span v-if="showType==='view'">{{addform.realName}}</span>
          <el-input v-else v-model="addform.realName" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <span v-if="showType==='view'">{{addform.mobile}}</span>
          <el-input v-else v-model="addform.mobile" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色：" prop="roleId">
          <el-radio-group v-model="addform.roleId">
            <el-radio
              v-for="(item, index) in addformrolelist"
              :key="index"
              :label="item.id">
              {{item.roleName}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号备注：" prop="memo">
          <span v-if="showType==='view'">{{addform.remark}}</span>
          <el-input v-else type="textarea" v-model="addform.remark"></el-input>
        </el-form-item>

        <!--<el-form-item v-if="showType==='add'" label="密码：" prop="password">
          <el-input v-model.trim="addform.password" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showType==='add'" label="确认密码：" prop="confirm_password">
          <el-input v-model.trim="addform.confirm_password" clearable></el-input>
        </el-form-item>-->
        <el-form-item label="账号状态：" prop="status" :disabled="showType==='view'">
          <!--<el-radio-group v-model="radio">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>-->
          <el-switch
            v-model="addform.status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

      </el-form>
      <!--编辑form-->
      <el-form
        v-show="showType === 'edit'"
        :model="editform"
        :rules="editformrules"
        ref="editform"
        label-width="130px">
        <el-form-item label="账号名称：" prop="name">
          <el-input v-model.trim="editform.name" clearable></el-input>
        </el-form-item>
        <el-form-item label="真实姓名：" prop="realName">
          <el-input v-model.trim="editform.realName" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话：" prop="mobile">
          <el-input v-model.trim="editform.mobile" clearable></el-input>
        </el-form-item>
         <el-form-item label="角色：" prop="roleIds">
           <el-radio-group v-model="editform.roleId">
             <el-radio
               v-for="(item, index) in addformrolelist"
               :key="index"
               :label="item.id">
               {{item.roleName}}
             </el-radio>
           </el-radio-group>
         </el-form-item>
        <el-form-item label="账号备注：" prop="remark">
          <el-input type="textarea" v-model="editform.remark"></el-input>
        </el-form-item>
        <el-form-item label="账号状态：" prop="status">
          <el-switch
            v-model="editform.status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>

      </el-form>
      <!--重置密码-->
      <el-form
        v-show="showType==='reset'"
        :model="resetform"
        :rules="resetformrules"
        ref="resetform"
        label-width="130px"
      >
        <el-form-item label="密码：" prop="password">
          <el-input v-model.trim="resetform.password" clearable></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirm_password">
          <el-input v-model.trim="resetform.confirm_password" clearable></el-input>
        </el-form-item>
      </el-form>

      <el-form class="tx-c" v-if="showType!=='view'">
          <el-button type="primary" @click="handleClick('sure')">{{btnword}}</el-button>
          <el-button @click="dialog=false">取 消</el-button>
        </el-form>
    </el-dialog>
  </el-container>
</template>

<script>
  //import { mapGetters } from "vuex";
  //import TableFilter from "@/components/TableFilter";
  import TableView from '@/components/TableView'
  import PaginationView from '@/components/PaginationView'
  import * as userManage from '@/api/main/account/userManage'
  import * as roleManage from "@/api/main/account/roleManage";

  export default {
    name: 'roleManage',
    components: {
      PaginationView,
      TableView
    },
    data() {
      const validateConfirmPassWord = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('密码必填'))
        } else {
          if (this.showType === 'add') {
            if (this.addform.password != this.addform.confirm_password) {
              return callback(new Error('密码不一致'))
            } else {
              callback()
            }
          } else {
            if (this.resetform.password != this.resetform.confirm_password) {
              return callback(new Error('密码不一致'))
            } else {
              callback()
            }
          }

        }
      }
      return {

        pageInfo: {
          pageNum: 1,
          pageSize: 20,
          mobile: '',
          name: '',
          roleId: ''
        },
        tableContent: [{
          field: 'name',
          label: '账号名称'
        }, {
          field: 'realName',
          label: '真实姓名'
        }, {
          field: 'mobile',
          label: '联系电话'
        },
        //   {
        //   field: 'roleName',
        //   label: '角色'
        // },
          {
          field: 'createdTime',
          label: '创建时间'
        }, {
          field: 'status',
          label: '状态'
        }, {
          field: 'remark',
          label: '备注'
        }, {
          field: 'operation',
          label: '操作'
        }],
        // editBtnMapList: ['view', 'update', 'reset','switchStatus'],  //自定义的按钮内容
        editBtnMapList: ['update', 'delete','reset'],  //自定义的按钮内容

        columnData: [],
        total: null,
        showType: 'add',     //添加账号 addform 编辑 editform 重置密码 resetpw
        addformrolelist: [],  //角色列表
        resetform: {
          id: '',
          password: '',
          confirm_password: ''
        },
        resetformrules: {
          password: [
            {required: true, min: 6, trigger: 'blur'}
          ],
          confirm_password: [
            {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
          ]
        },
        addform: {
          "createdTime": "",
          "deviceId": "",
          "deviceOs": "",
          "mobile": "",
          "name": "",
          "nickName": "",
          "project": "",
          "realName": "",
          "remark": "",
          "roleId": '',
          "status": true,
          "tenantName": ""
        },
        editform: {
          "createdTime": "",
          "deviceId": "",
          "deviceOs": "",
          "id": '',
          "mobile": "",
          "name": "",
          "nickName": "",
          "project": "",
          "realName": "",
          "remark": "",
          "roleId": '',
          "status": '',
          "tenantName": ""
        },
        editformrules: {
          realName: [
            {required: true, message: '请输入姓名'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符'}
          ],
          roleId: [
            {required: true, message: '请选择角色', trigger: 'change'}
          ],
          mobile: [
            {required: true, message: '请输入11位手机号', min: 11, max: 11}
          ],
          password: [
            {required: true, min: 6, trigger: 'blur'}
          ],
          confirm_password: [
            {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        },
        addformrules: {
          name: [
            {required: true,  trigger: 'blur',message: '请输入账号姓名'}
          ],
          realName: [
            {required: true, message: '请输入姓名'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符'}
          ],
          roleId: [
            {required: true, message: '请选择角色', trigger: 'change'}
          ],
          mobile: [
            {required: true, message: '请输入11位手机号', min: 11, max: 11}
          ],
          password: [
            {required: true, min: 6, trigger: 'blur'}
          ],
          confirm_password: [
            {required: true, validator: validateConfirmPassWord, trigger: 'blur'}
          ],
          status: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        },
        showtitle: '添加账号',
        btnword: '确定',
        dialog: false
      }
    },
    methods: {
      submitForm(formName) {
        this.getData()
      },
      resetForm(formName) {
        this.pageInfo = {
          pageNum: 1,
          pageSize: 20,
          mobile: '',
          name: '',
          roleId: ''
        }
        this.dialog = false
        this.getData()
      },
      addAccountBtn() {
        this.setTitleType('添加账号', 'add', '确定')
      },

      editBtnClick(val, type) {
        let _this = this
        switch (type) {
          case 'update':
            debugger
            this.updateId = val.id
            _this.setTitleType('编辑账号', 'edit', '确定')
            _this.getUserInfo(val.id)
            break
          case 'view':
            _this.setTitleType('查看账号', 'view', '')
            _this.getUserInfo(val.id)
            break
          case 'reset':
            // _this.setTitleType('重置密码', 'reset', '确定')
            // _this.getUserInfo(val.id)
            this.$confirm(`确定重置密码吗？重置将恢复初始密码！是否继续?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              userManage.resetPassword(val.id).then(res=>{
                this.handleMessage(res)
                this.getData()
              })
            })
            break
          case 'delete':
            _this.delUser(val.id)
            break
          case 'switchStatus':
            _this.changeUserStatus(val.id, val.status ? 0 : 1)
            break
        }
      },

      handleClick(type) {
        let _this = this
        let _refstype = _this.showType //添加账号 addform 编辑 editform 重置密码 resetpw
        _this.$refs[_refstype + 'form'].validate((valid) => {
          if (valid) {
            switch (_refstype) {
              case 'add':
                userManage.create(_this.addform).then(res => {
                  _this.handleMessage(res)
                  if(res.code === '200')_this.getData()
                })
                break
              case 'edit':
                userManage.update(this.updateId,_this.editform,).then(res => {
                  _this.handleMessage(res)
                  if(res.code === '200')_this.getData()
                })
                break
              case 'reset':
                /* userManage.createUser(_this.resetform, 'reset').then(res => {
                     _this.resetForms()
                 })*/
                break
              default:
                return null
            }}
        })
    },
    setTitleType(title = '', type = 'addform', btnwold = '确定') {
      let _this = this
      _this.dialog = true
      _this.showtitle = title
      _this.showType = type
      _this.btnword = btnwold
    },
    resetForms() {
      let _this = this

      let type = _this.showType
      switch (type) {
        case 'add':
          _this.addform = {
            "createdTime": "",
            "deviceId": "",
            "deviceOs": "",
            "mobile": "",
            "name": "",
            "nickName": "",
            "project": "",
            "realName": "",
            "remark": "",
            "roleId": '',
            "status": true,
            "tenantName": ""
          }
          if (_this.$refs.addform) {
            _this.$refs.addform.resetFields()
          }
          break
        case 'edit':
          _this.editform = {
            "createdTime": "",
            "deviceId": "",
            "deviceOs": "",
            "mobile": "",
            "name": "",
            "nickName": "",
            "project": "",
            "realName": "",
            "remark": "",
            "roleId": '',
            "status": true,
            "tenantName": ""
          }
          _this.$refs.editform.resetFields()
          break
        case 'reset':
          _this.resetform = {
            id: '',
            password: '',
            confirm_password: ''
          }
          _this.$refs.resetform.resetFields()
          break
      }
      _this.dialog = false

    },
    //更改用户状态
    changeUserStatus(id, enabled) {
      userManage.changeUserStatus(id, enabled).then((res) => {
        this.handleMessage(res)
        if (res.code === '200') this.getData()
      })
    },
    //删除用户
    delUser(id) {
      userManage.deleteIt(id).then((res) => {
        this.handleMessage(res)
        this.getData()
      })
    },
    //拉取列表
    getData() {
      userManage.getUserList(this.pageInfo).then(res => {
        if(res.code !=='200') return this.$message.error(res.message)
        this.columnData = res.body.records
        this.total = Number(res.body.total)
        this.pageInfo.pageNumber = Number(res.body.current) || 1
        this.resetForms()
      })
    },
    getUserInfo(id) {
      let _this = this
      let type = _this.showType
      userManage.getUser(id).then(res => {
        if (res.code === '200') {
          switch (type) {
            case 'view':
              _this.addform = res.body
              break
            case 'edit':
              _this.editform = res.body
              break
            case 'reset':
              _this.resetform.id = res.body.id
              break
          }
        }
      })
    },
    getRoleAll() {

      roleManage.getRoleList({}).then(res => {
        if (res.code === '200') {
          this.addformrolelist = res.body.records
        }
      })
    },
    // pageSize变化函数
    sizeChange(val) {
      this.pageInfo.pageSize = val
      this.getData()
    },
    // page变化函数
    pageChange(val) {
      this.pageInfo.pageNumber = val
      this.getData()
    }
  }
  ,
  computed: {
    // ...mapGetters(["tableContent"])
  }
  ,
  created: function () {
    this.getData()
    this.getRoleAll()
  }
  }
</script>
<style lang="scss">

</style>

